<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <el-button type="primary" :icon="Plus" size="default" @click="addTrademark">添加</el-button>

        </div>
      </template>
      <el-table :style="{ marginBottom: '20px' }" :data="tableData">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #default="{ row }">
            <img :src="row.logoUrl" height="100" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="warning" :icon="Edit" size="small" @click="UpdateTrademark(row)">修改</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteTrademark(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:page-size="limit" v-model:current-page="page" layout="prev, pager, next,sizes"
        :page-sizes="[3, 5, 7, 9, 11]" :total="total" />

    </el-card>



    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id ? '修改品牌' : '新增品牌'">
      <el-form label-width="100px" :model="newTrademark" :rules="addTrademarkRule" ref="fromref">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="newTrademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${baseURL}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="AddOrUpdateTrademark">确认</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { requestTrademarkList, requestAddTrademark, requestUpdateTrademark, requestDeleteTrademark } from '@/api/trademark'
import type { trademarkListReturnType, trademarkListReturnRecordsItemType, trademarkListReturnRecordsType } from '@/api/trademark'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'



//1.table逻辑
const tableData = ref<trademarkListReturnRecordsType>([])

interface pageDataType {
  page: number;
  limit: number;
  total: number;
}
//2.页码逻辑
const pageData = ref<pageDataType>({
  page: 1,
  limit: 3,
  total: 30
})
const { page, limit, total } = toRefs(pageData.value)

//3.对话框逻辑
const dialogFormVisible = ref(false)
const baseURL = import.meta.env.VITE_API_URL

//表单和图片是需要收集起来发送请求的
const newTrademark = ref<trademarkListReturnRecordsItemType>({
  tmName: '',
  logoUrl: '',
  id: 0
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // console.log(response);
  // console.log(URL.createObjectURL(uploadFile.raw!));

  newTrademark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//2.点击添加的逻辑
const addTrademark = () => {
  //点击添加,展开表格,清空表格内容
  newTrademark.value = {
    tmName: '',
    logoUrl: '',
    id: 0
  }
  dialogFormVisible.value = true
}

//3.点击修改的逻辑
//点击修改获取当前行的数据,把nowTrademark的值改成当前的row,展开表格
const UpdateTrademark = (row: trademarkListReturnRecordsItemType) => {
  //打开表单前先清空表单的校验
  fromref.value?.clearValidate()

  dialogFormVisible.value = true

  // console.log(row, 'row', newTrademark);
  newTrademark.value = { ...row }

}

//4.点击确认发送请求
const fromref = ref<FormInstance>()
const AddOrUpdateTrademark = async () => {
  try {  //点击确认时先进行全局校验
    await fromref.value?.validate()
    dialogFormVisible.value = false
    //根据有无id确定是更新还是新增
    //有id是更新,发送更新请求
    try {
      if (newTrademark.value.id) {
        await requestUpdateTrademark(newTrademark.value)
        ElMessage.success('更新成功')
      } else {
        await requestAddTrademark(newTrademark.value)
        ElMessage.success('新增成功')
        //新增后回到第一页
        page.value = 1
      }
    } catch (e) {
      ElMessage.error(newTrademark.value.id ? '更新错误' : '新增错误')
    }
    //发送请求后重新发送列表请求
    getTrademarkList()
  } catch (e) {
    // ElMessage.error('请输入正确的内容')
  }
}


//5.点击删除逻辑
const deleteTrademark = (id: number) => {
  //关闭前弹框
  ElMessageBox.confirm(
    '是否确定删除该品牌',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await requestDeleteTrademark(id)
        ElMessage.success('删除成功')
        getTrademarkList()
      } catch (e) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })


}


//6.表单验证逻辑
//自定义表单校验规则
const checkTMNameLength = (rule: any, value: string, callback: any) => {
  //value:当前需要被校验的值
  //callback是回调函数,如果有参数则代表错误信息,如果没有参数则代表直接放行
  // console.log(rule, 'rule');

  if (value.length < 2 || value.length > 5) {
    callback('长度必须是2-5')
  } else {  
    callback()
  }
}

const addTrademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: '必须填写品牌名称', trigger: 'blur' },
    { validator: checkTMNameLength, trigger: 'blur' },
  ],
  logoUrl: [
    { required: true, message: '必须上传文件', trigger: 'blur' },
  ]
})





//1.初始化的时候请求品牌列表
onMounted(() => {
  getTrademarkList()
})
const getTrademarkList = async () => {
  const result = await requestTrademarkList({ page: page.value, limit: limit.value })
  tableData.value = result.records
  total.value = result.total
};

//监听limit和page变化重新发送请求
watch([limit, page], () => {
  getTrademarkList()
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  
  <style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>